import {ref, onMounted} from 'vue'

// 参数urlToGetPubKey表示获得公钥的地址，如不提供，则是comm/auth/get-rsa-public-key
export function useJsencryptHelper(urlToGetPubKey?:string): (plainPassword: string)=>string {

  const publicKey = ref('')
  /* eslint-disable */
  const encPassword = function(plainPassword:string){
    let encrypt = new window.JSEncrypt();
    encrypt.setPublicKey(publicKey.value)
    return encrypt.encrypt(plainPassword)
  }

  onMounted(() => {
    if($f.globalCfg.encTransPwd){
      if (!window.JSEncrypt) {
        const script = document.createElement('script')
        script.type = 'text/javascript'
        script.src = $f.getSiteUrl('jsencrypt.min.js')
        document.body.appendChild(script)
      }
      $f.axios.get<string>(urlToGetPubKey ?? 'comm/auth/get-rsa-public-key')
        .then((resp)=>{
          publicKey.value = resp.data
        }).catch((err) => {
          $f.ui.showNotifyFailed($f.getAxiosErrMsg(err))
        })
    }
  })

  return encPassword
}

